package game.games.gol;

import game.GameListener;
import game.Logger;
import game.Util;
import game.cellmap.AbstractCellMapGame;
import game.cellsize.ICellSizeChangeListener;
import game.console.GameConsole;
import game.console.IConsoleCommand;
import game.games.carcassonne.IterablePoint;
import game.scrollable.INeverScrollable;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

import javax.swing.SwingUtilities;

// @FullScreen
public class GameOfLife extends AbstractCellMapGame<GameOfLifeCellMap> implements INeverScrollable, ICellSizeChangeListener
{
    private static GameOfLife instance;
    
    public synchronized static GameOfLife getInstance()
    {
        if (instance == null)
        {
            synchronized (GameOfLife.class)
            {
                instance = new GameOfLife();
                for (IConsoleCommand commandObj : GameOfLifeCommands.getCommands())
                {
                    GameConsole.getInstance().addConsoleCommand(commandObj);
                }
            }
        }
        return instance;
    }
    
    private int            generation           = 0;
    private int            livingCells          = 0;
    private int            livingCellsIdentical = 0;
    private int            nextLivingCells      = 15000;
    
    private GameOfLifeRule rule                 = GameOfLifeRule.DEFAULT;
    
    private ColorSet       colorSet             = ColorSet.DEFAULT;
    private static boolean CREATE_LIVE_MODE     = false;
    
    public GameOfLife()
    {
        super(false, new GameOfLifeCellMap());
        final GameListener gameListener = GameListener.getInstance();
        gameListener.addKeyListener(new KeyAdapter() {
            private boolean IGNORE_KEYBOARD = false;
            
            @Override
            public void keyPressed(KeyEvent e)
            {
                if (IGNORE_KEYBOARD)
                {
                    e.consume();
                }
                else
                {
                    IGNORE_KEYBOARD = true;
                    final GameConsole console = GameConsole.getInstance();
                    if (console.isOpen() == false)
                    {
                        switch (e.getKeyCode())
                        {
                            case KeyEvent.VK_P:
                            {
                                if (instance.isPaused())
                                {
                                    instance.resume();
                                }
                                else if (instance.isRunning())
                                {
                                    instance.pause();
                                }
                                break;
                            }
                            case KeyEvent.VK_S:
                            {
                                instance.stop();
                                break;
                            }
                            case KeyEvent.VK_R:
                            {
                                instance.restart();
                                break;
                            }
                            default:
                            {
                                getMap().getKeyAdapter().keyPressed(e);
                                break;
                            }
                        }
                    }
                    IGNORE_KEYBOARD = false;
                }
            }
        });
        gameListener.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e)
            {
                if (SwingUtilities.isRightMouseButton(e))
                {
                    CREATE_LIVE_MODE = CREATE_LIVE_MODE == false;
                    Logger.log("CREATIVE_LIVE_MODE " + CREATE_LIVE_MODE);
                }
            }
        });
        gameListener.addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseMoved(MouseEvent e)
            {
                if (CREATE_LIVE_MODE)
                {
                    try
                    {
                        Logger.log("SURVIVING: " + getMousePoint());
                        Cell cell = getMap().getCells().getValue(getMousePoint());
                        cell.setAlive(true);
                        cell.setSurviving(true);
                    }
                    catch (IllegalArgumentException ex)
                    {
                        ex.printStackTrace();
                    }
                }
            }
        });
    }
    
    public void setRule(String rule)
    {
        GameOfLifeRule newRule = new GameOfLifeRule(rule);
        setRule(newRule);
    }
    
    public void setRule(GameOfLifeRule newRule)
    {
        try
        {
            pause();
            rule = newRule;
            resume();
        }
        catch (Exception ex)
        {
            Logger.log(ex);
        }
    }
    
    public void setNextLivingCells(int livingCells)
    {
        if (livingCells > getMap().getCells().countValues())
        {
            livingCells = getMap().getCells().countValues();
        }
        this.nextLivingCells = livingCells;
    }
    
    public void setProzentLivingCells(int prozent)
    {
        if (prozent >= 100)
        {
            setNextLivingCells(getMap().getCells().countValues());
        }
        else
        {
            setNextLivingCells((getMap().getCells().countValues() / 100) * prozent);
        }
    }
    
    private final int maxThreads = 8;
    
    private class RandomLivingCellThread extends Thread
    {
        private List<Point> livingCells = new ArrayList<Point>();
        
        public RandomLivingCellThread(String string)
        {
            super(string);
        }
        
        public List<Point> getLivingCells()
        {
            return livingCells;
        }
        
        @Override
        public void run()
        {
            // Lebende Zellen generieren
            Random RANDOM = new Random(System.nanoTime());
            do
            {
                Point index = new Point(RANDOM.nextInt(getMap().getMapSize().width), RANDOM.nextInt(getMap().getMapSize().height));
                if (livingCells.contains(index) == false)
                {
                    livingCells.add(index);
                }
            }
            while (livingCells.size() < 250);
        }
    }
    
    private static Thread AddLivingCellsThreadInstance = null;
    
    private class AddLivingCellsThread implements Runnable
    {
        private int cellsFound = 0;
        
        @Override
        public void run()
        {
            long startTime = System.nanoTime();
            final List<Point> livingCells = Collections.synchronizedList(new ArrayList<Point>());
            do
            {
                List<RandomLivingCellThread> threads = new ArrayList<RandomLivingCellThread>();
                while (isReset() && threads.size() < maxThreads)
                {
                    RandomLivingCellThread t = new RandomLivingCellThread("RandomLivingCellsThread " + threads.size());
                    t.start();
                    threads.add(t);
                }
                for (RandomLivingCellThread thread : threads)
                {
                    while (isReset() && thread.isAlive())
                    {
                        // return
                        try
                        {
                            thread.join();
                        }
                        catch (InterruptedException e)
                        {
                            //
                        }
                    }
                    List<Point> cellPoints = thread.getLivingCells();
                    for (Point p : cellPoints)
                    {
                        if (livingCells.contains(p) == false)
                        {
                            livingCells.add(p);
                        }
                    }
                }
                cellsFound = livingCells.size();
                Logger.log(Thread.currentThread().getName() + ": " + cellsFound + " cells of " + nextLivingCells + " found");
            }
            while (isReset() && livingCells.size() < nextLivingCells);
            while (isReset() && livingCells.size() > nextLivingCells)
            {
                // return
                livingCells.remove(0);
            }
            Logger.log(livingCells.size() + " living cells found (" + Util.nanoToSec(System.nanoTime() - startTime) + " sec)");
            // reset count
            for (Point index : livingCells)
            {
                // return
                if (isReset() == false)
                {
                    break;
                }
                Cell cell = getMap().getCells().getValue(index);
                cell.setAlive(true);
                cell.setSurviving(true);
            }
        }
    }
    
    private void addLivingCells()
    {
        if (AddLivingCellsThreadInstance == null)
        {
            AddLivingCellsThreadInstance = new Thread(new AddLivingCellsThread(), "AddLivingCellsThread");
            AddLivingCellsThreadInstance.start();
        }
        while (AddLivingCellsThreadInstance.isAlive())
        {
            try
            {
                AddLivingCellsThreadInstance.join();
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
        AddLivingCellsThreadInstance = null;
    }
    
    @Override
    protected void reset()
    {
        super.reset();
        long startTime = System.nanoTime();
        // init
        getMap().addCellSizeChangeListener(this);
        getMap().setCellSizes(1, 3, 5, 7, 10, 12, 15, 18, 20, 25);
        // Anzahl Zellen
        Dimension size = getFrameSize();
        Dimension maxSize = getMap().calcMaxSize(size);
        // Liste generieren
        getMap().setMapSize(maxSize);
        if (nextLivingCells > getMap().getCells().countValues())
        {
            setProzentLivingCells(25);
        }
        Logger.log("initGeneration(" + maxSize.getWidth() + "/" + maxSize.getHeight() + ") complete, " + getMap().getCells().countValues() + " cells created (" + +Util.nanoToSec(System.nanoTime() - startTime) + " sec)");
    }
    
    @Override
    protected void start()
    {
        Logger.log("start()");
        long startTime = System.nanoTime();
        recalcSize(getFrameSize());
        getMap().sync();
        Logger.log("resetGeneration(" + getMap().getCells().countValues() + ") (" + Util.nanoToSec(System.nanoTime() - startTime) + " sec)");
        addLivingCells();
        generation = 0;
        super.start();
    }
    
    public void setColorSet(ColorSet colorSet)
    {
        this.colorSet = colorSet;
    }
    
    public ColorSet getColorSet()
    {
        if (colorSet == null)
        {
            colorSet = ColorSet.DEFAULT;
        }
        return colorSet;
    }
    
    @Override
    public BufferedImage getImage()
    {
        Dimension mapSize = getMap().getCellMapSize();
        // image
        BufferedImage image = new BufferedImage(mapSize.width, mapSize.height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = image.createGraphics();
        for (IterablePoint<Cell> i = getMap().getCells().getIterator(); i.hasNext();)
        {
            Point position = i.getCurrentPoint();
            Cell cell = i.next();
            Color color = getColorSet().getColor(cell.isAlive(), cell.isSurviving());
            getMap().fillRect(g, position, color);
            if (isPaused() == false)
            {
                // next round
                cell.setAlive(cell.isSurviving());
            }
        }
        return image;
    }
    
    @Override
    public void doNext()
    {
        generation++;
        int alive = 0;
        for (IterablePoint<Cell> i = getMap().getCells().getIterator(); i.hasNext();)
        {
            Cell cell = i.next();
            int livingNeighbors = cell.countLivingNeighbors();
            cell.setSurviving(rule.isSurviving(cell.isAlive(), livingNeighbors));
            if (cell.isAlive())
            {
                alive++;
            }
        }
        if (alive == livingCells)
        {
            livingCellsIdentical++;
        }
        else
        {
            livingCellsIdentical = 0;
        }
        livingCells = alive;
        setInfo("Generation " + generation + "; " + livingCells + " Living Cells");
        if (livingCells <= 0)
        {
            Logger.log("No more living cells");
            restart();
        }
        else if (livingCellsIdentical > 50)
        {
            restart();
        }
    }
    
    public static void main(String[] args)
    {
        Thread t = new Thread(GameOfLife.getInstance(), "GameOfLife");
        t.start();
    }
    
    @Override
    public void recalcSize(Dimension windowSize)
    {
        Dimension maxXY = getMap().calcMaxSize(windowSize);
        if (maxXY.equals(getMap().getMapSize()) == false)
        {
            getMap().setMapSize(maxXY);
            int prozentLivingCells = 30;
            if (getMap().getCellSize() < 10)
            {
                prozentLivingCells = 5;
            }
            setProzentLivingCells(prozentLivingCells);
        }
    }
    
    @Override
    public void cellSizeChanged(int newCellSize)
    {
        restart();
    }
}
